import {GridContent, PageContainer} from '@ant-design/pro-components';
import {Cascader, Empty, Result, Spin} from 'antd';
import React, {useLayoutEffect, useRef, useState} from 'react';
import useStyles from './style.style';
import {list} from '../categories/service';
import {useModel, useRequest} from '@umijs/max';
import CustomLeafTreeData from "./components/CustomLeafTreeData";
import CustomRootTreeData from "./components/CustomRootTreeData";

type SettingsStateKeys = 'base' | 'security' | 'binding' | 'notification';
type SettingsState = {
  mode: 'inline' | 'horizontal';
  selectKey: SettingsStateKeys;
};

interface Option {
  value: string | number;
  label: string;
  children?: Option[];
}

const Filter: React.FC = () => {
  const {initialState} = useModel('@@initialState');
  const {styles} = useStyles();
  // const [searchParams, setSearchParams] = useSearchParams()
  const [initConfig, setInitConfig] = useState<SettingsState>({
    mode: 'inline',
    selectKey: 'base',
  });
  const dom = useRef<HTMLDivElement>();

  const resize = () => {
    requestAnimationFrame(() => {
      if (!dom.current) {
        return;
      }
      let mode: 'inline' | 'horizontal' = 'inline';
      const {offsetWidth} = dom.current;
      if (dom.current.offsetWidth < 641 && offsetWidth > 400) {
        mode = 'horizontal';
      }
      if (window.innerWidth < 768 && offsetWidth > 400) {
        mode = 'horizontal';
      }
      setInitConfig({
        ...initConfig,
        mode: mode as SettingsState['mode'],
      });
    });
  };

  useLayoutEffect(() => {
    if (dom.current) {
      window.addEventListener('resize', resize);
      resize();
    }
    return () => {
      window.removeEventListener('resize', resize);
    };
  }, [dom.current]);

  const [cascaderVal, setCascaderVal] = useState<(string | number)[]>([])
  const [selectedOptions, setSelectedOptions] = useState<any[]>([])
  const [cascaderOptions, setCascaderOptions] = useState<Option[]>([]);
  const [loadCasDataLoading, setLoadCasDataLoading] = useState(false)
  // console.log('selectedOptions', selectedOptions);
  const onCasChange = (value: (string | number)[], selectedOptions: Option[]) => {
    // console.log(value, selectedOptions);
    setCascaderVal(value)
    setSelectedOptions(selectedOptions)
  };

  const loadCasData = async (selectedOptions: any[]) => {
    const targetOption = selectedOptions[selectedOptions.length - 1];
    setLoadCasDataLoading(true)
    const {data} = await list({
      parentId: targetOption?.id
    })
    if (!data?.length) {
      targetOption.isLeaf = true
    }
    targetOption.children = data?.map(item => {
      return {
        ...item,
        title: item.name,
        value: item.id,
        label: item.name,
        key: item.id,
        isLeaf: false
      }
    });
    setLoadCasDataLoading(false)
    setCascaderOptions([...cascaderOptions]);
  };

  // 左侧分类
  const {loading: typeLoading} = useRequest(() => {
    return list({
      level: 1,
      parentId: null
    });
  }, {
    onSuccess(res: any[]) {
      const ret = res?.map((item: any) => ({
        ...item,
        title: item.name,
        value: item.id,
        label: item.name,
        key: item.id,
        isLeaf: false,
      }))
      // console.log(ret);
      setCascaderOptions(ret)
    },
  });

  /**
   * 叶子分类树配置
   */
  const [leafTreeData, setLeafTreeData] = useState([])
  const [leafTreeLoading, setLeafTreeLoading] = useState(false)

  /**
   * 一级分类树配置
   */
  const [rootTreeData, setRootTreeData] = useState([])

  return (
    <PageContainer content="支持创建和设计筛选字段，适合需要动态配置的场景。">
      <GridContent>
        <div
          className={styles.main}
          ref={(ref) => {
            if (ref) {
              dom.current = ref;
            }
          }}
        >
          <div className={styles.leftMenu}>
            <Spin spinning={typeLoading}>
              <Cascader.Panel
                style={{
                  color: initialState?.settings?.navTheme === 'realDark' ? '#fff' : undefined
                }}
                value={cascaderVal}
                options={cascaderOptions}
                loadData={loadCasData}
                onChange={onCasChange}
                changeOnSelect
              />
            </Spin>

          </div>
          <div className={styles.right}>
            <div className={styles.title}>{selectedOptions?.map(item => item.name)?.join('/')} 筛选条件设置</div>
            <Spin spinning={leafTreeLoading}>
              <div style={{
                backgroundColor: 'rgba(223, 223, 223,.17)',
                padding: '15px 0',
                minHeight: 200,
                display: 'flex',
                flexDirection: 'column',
                // justifyContent: 'center'
              }}>
                {/*选中叶子分类*/}
                {!!selectedOptions?.[selectedOptions?.length - 1]?.isLeaf && <>
                  <CustomLeafTreeData
                    cascaderVal={cascaderVal}
                    treeData={leafTreeData}
                    setTreeData={setLeafTreeData}
                    onLoading={setLeafTreeLoading}
                  />
                </>}
                {/*选中一级分类*/}
                {!loadCasDataLoading
                  && selectedOptions?.length === 1
                  && selectedOptions?.[0]?.level === 1
                  && !selectedOptions?.[0]?.isLeaf &&
                  <CustomRootTreeData
                    cascaderVal={cascaderVal}
                    treeData={rootTreeData}
                    setTreeData={setRootTreeData}
                  />}
                {/*选中非一级分类 & 非叶子分类*/}
                {!loadCasDataLoading
                  && selectedOptions?.length > 0
                  && !selectedOptions?.[selectedOptions?.length - 1]?.isLeaf
                  && !(selectedOptions?.length === 1 && selectedOptions?.[0]?.level === 1) &&
                  <Result title={'请选择叶子分类'}/>}
                {/*未选中*/}
                {!selectedOptions?.length && <Result title={'请选择分类'}/>}
              </div>
            </Spin>
          </div>
        </div>
      </GridContent>
    </PageContainer>

  );
};

export default Filter;
